package com.cgbl.service

import android.bluetooth.le.ScanSettings
import android.content.Context
import cn.bingoogolapple.swipebacklayout.BGASwipeBackHelper
import cn.jpush.android.api.JPushInterface
import cn.wandersnail.ble.EasyBLE
import cn.wandersnail.ble.ScanConfiguration
import cn.wandersnail.ble.ScannerType
import cn.wandersnail.commons.poster.ThreadMode
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ColorUtils
import com.cgbl.service.im.NimSDKOptionConfig
import com.cgbl.service.im.push.PushMessageHandler
import com.cgbl.service.im.utils.Constant
import com.cgbl.service.im.utils.DataUtils
import com.cgbl.service.utils.city.CityUtils
import com.netease.nimlib.sdk.SDKOptions
import com.netease.yunxin.kit.alog.ALog
import com.netease.yunxin.kit.corekit.im.IMKitClient
import com.netease.yunxin.kit.corekit.im.IMKitClient.registerMixPushMessageHandler
import com.netease.yunxin.kit.corekit.im.IMKitClient.toggleNotification
import com.netease.yunxin.kit.corekit.im.repo.SettingRepo.isPushNotify
import com.netease.yunxin.kit.corekit.im.utils.IMKitUtils.isMainProcess
import com.robot.base.configs.AppConstants
import com.robot.base.configs.PrefsManager
import com.robot.base.util.AppUtils
import com.robot.base.util.DensityAdaptationUtils
import com.robot.base.util.ToastUtils
import com.robot.base.util.debounce.AntiShake
import com.scwang.smartrefresh.header.MaterialHeader
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.footer.ClassicsFooter
import com.tencent.tauth.Tencent
import com.umeng.commonsdk.UMConfigure
import com.umeng.socialize.PlatformConfig
import me.goldze.mvvmhabit.base.BaseApplication
import me.goldze.mvvmhabit.crash.CaocConfig
import me.goldze.mvvmhabit.utils.KLog
import me.goldze.mvvmhabit.utils.Utils

class GlApp : BaseApplication() {

    companion object {
        private var context: GlApp? = null
        private const val UM_KEY = "586c904907fe656adc00197a"
        const val WX_KEY = "wx3ba86c39e9dd9309"

        // APP_ID 替换为你的应用从官方网站申请到的合法appID
        const val APP_ID = "wxdee98193ad267356"
        var mApp: GlApp? = null
        var mAntiShake: AntiShake? = null
        var phoneCount = 0
        var isCheck = false

        fun getInstance(): GlApp {
            return mApp!!
        }

        @JvmStatic
        fun getContext(): Context? {
            return context
        }

        //static 代码段可以防止内存泄露
        init {
            //设置全局的Header构建器
            SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, _ ->
                MaterialHeader(context)
            }
            //设置全局的Footer构建器
            SmartRefreshLayout.setDefaultRefreshFooterCreator { context, _ ->
                ClassicsFooter.REFRESH_FOOTER_FINISH = "加载中..."
                ClassicsFooter.REFRESH_FOOTER_LOADING = "加载中..."
                ClassicsFooter.REFRESH_FOOTER_NOTHING = "已经全部加载完毕"
                ClassicsFooter(context).setDrawableSize(20f)
            }
        }
    }

    override fun onCreate() {
        super.onCreate()
        context = this
        AppUtils.init(this)
        Utils.init(this)
        PrefsManager.load(this)
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
        if (mAntiShake == null) {
            mAntiShake = AntiShake()
        }
//        var inputStream: InputStream? = null
//        try {
//            inputStream = assets.open("tasklist.xml")
//            AlphaManager.getInstance(this).addProjectsViaFile(inputStream)
//        } catch (ex: IOException) {
//            ex.printStackTrace()
//        } finally {
//            AlphaUtils.closeSafely(inputStream)
//        }
        ARouter.openDebug()
        ARouter.init(this)
        BGASwipeBackHelper.init(this, null)
//        AlphaManager.getInstance(this).start()
        //是否开启日志打印
        KLog.init(true)
        //配置全局异常崩溃操作
        DensityAdaptationUtils.setDensity(context!!, 375f)
        CaocConfig.Builder.create().backgroundMode(CaocConfig.BACKGROUND_MODE_SILENT) //背景模式,开启沉浸式
            .enabled(true) //是否启动全局异常捕获
            .showErrorDetails(true) //是否显示错误详细信息
            .showRestartButton(true) //是否显示重启按钮
            .trackActivities(true) //是否跟踪Activity
            .minTimeBetweenCrashesMs(2000) //崩溃的间隔时间(毫秒)
            .errorDrawable(R.mipmap.ic_launcher) //错误图标
            //                .restartActivity(LoginActivity.class) //重新启动后的activity
            //.errorActivity(YourCustomErrorActivity.class) //崩溃后的错误activity
            //.eventListener(new YourCustomEventListener()) //崩溃后的错误监听
            .apply()
        initDir()
        initUIKit()
        initUMShare()
        initUMPush()
        ToastUtils.setMsgColor(ColorUtils.getColor(R.color.app_white))
        ToastUtils.setBgColor(ColorUtils.getColor(R.color.app_2E000000))

        val scanConfig: ScanConfiguration = ScanConfiguration().setScanSettings(
            ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) //搜索模式
                .build()
        ).setScanPeriodMillis(Int.MAX_VALUE) //搜索周期
            .setAcceptSysConnectedDevice(false) //是否将系统蓝牙已连接的设备放到搜索结果中
//            .setOnlyAcceptBleDevice(false) //是否过滤非ble设备

        val ble: EasyBLE = EasyBLE.getBuilder().setScanConfiguration(scanConfig)
            .setScannerType(ScannerType.LE) //指定蓝牙扫描器，默认为系统Android5.0以上使用ScannerType.LE
            .setObserveAnnotationRequired(false) //不强制使用{@link Observe}注解才会收到被观察者的消息，强制使用的话，性能会好一些
            .setMethodDefaultThreadMode(ThreadMode.MAIN) //指定回调方法和观察者方法的默认线程
            .build()
        ble.setLogEnabled(false)
        ble.initialize(this)
        CityUtils.initJsonData()
    }

    private fun initUMShare() {
        /**
         * 初始化common库
         * 参数1:上下文，不能为空
         * 参数2:【友盟+】 AppKey
         * 参数3:【友盟+】 Channel
         * 参数4:设备类型，UMConfigure.DEVICE_TYPE_PHONE为手机、UMConfigure.DEVICE_TYPE_BOX为盒子，默认为手机
         * 参数5:Push推送业务的secret
         */
//        UMConfigure.init(this, BizConstant.UMENG_APPKEY, ChannelUtil.getChannel(this, BizConstant.DEFAULT_CHANNEL), UMConfigure.DEVICE_TYPE_PHONE, BizConstant.UMENG_MSG_SECRET)
//        UMShareAPI.get(this) //初始化sdk
//        PlatformConfig.setWeixin(BizConstant.WX_APP_ID, BizConstant.WX_APP_SECRET)
        //新浪微博(第三个参数为回调地址)
//        PlatformConfig.setSinaWeibo(BizConstant.WEIBO_APP_ID, BizConstant.WEIBO_APP_SECRET, BizConstant.WEIBO_REDIRECT_URL)
        //QQ
//        PlatformConfig.setQQZone(BizConstant.QQ_APP_ID, BizConstant.QQ_APP_SECRET)
        UMConfigure.init(
            this, "62315a002b8de26e11ffdd4e", "umeng", UMConfigure.DEVICE_TYPE_PHONE, ""
        );
        // 微信设置
        PlatformConfig.setWeixin(AppConstants.BizKey.WX_APP_ID, AppConstants.BizKey.WX_APP_SECRET);
        PlatformConfig.setWXFileProvider("com.tencent.sample2.fileprovider");
// QQ设置
        PlatformConfig.setQQZone(AppConstants.BizKey.QQ_APP_ID, AppConstants.BizKey.QQ_APP_SECRET);
        PlatformConfig.setQQFileProvider("com.tencent.sample2.fileprovider");
// 新浪微博设置
        PlatformConfig.setSinaWeibo(
            AppConstants.BizKey.WEIBO_APP_ID,
            AppConstants.BizKey.WEIBO_APP_SECRET,
            AppConstants.BizKey.WEIBO_REDIRECT_URL
        );
        PlatformConfig.setSinaFileProvider("com.tencent.sample2.fileprovider");
        //QQ官方sdk授权
        Tencent.setIsPermissionGranted(true);
//钉钉设置
//        PlatformConfig.setDing("dingoalmlnohc0wggfedpk");
//        PlatformConfig.setDingFileProvider("com.tencent.sample2.fileprovider");
// 企业微信设置
//        PlatformConfig.setWXWork("wwac6ffb259ff6f66a","EU1LRsWC5uWn6KUuYOiWUpkoH45eOA0yH-ngL8579zs","1000002","wwauthac6ffb259ff6f66a000002");
//        PlatformConfig.setWXWorkFileProvider("com.tencent.sample2.fileprovider");
// 其他平台设置
//        PlatformConfig.setDing("dingoalmlnohc0wggfedpk");
//        PlatformConfig.setYixin("yxc0614e80c9304c11b0391514d09f13bf");
//        PlatformConfig.setAlipay("2015111700822536");
//        PlatformConfig.setLaiwang("laiwangd497e70d4","d497e70d4c3e4efeab1381476bac4c5e");
//        PlatformConfig.setTwitter("3aIN7fuF685MuZ7jtXkQxalyi","MK6FEYG63eWcpDFgRYw4w9puJhzDl0tyuqWjZ3M7XJuuG7mMbO");
//        PlatformConfig.setPinterest("1439206");
//        PlatformConfig.setKakao("e4f60e065048eb031e235c806b31c70f");
//        PlatformConfig.setVKontakte("5764965","5My6SNliAaLxEm3Lyd9J");
//        PlatformConfig.setDropbox("oz8v5apet3arcdy","h7p2pjbzkkxt02a");
//        PlatformConfig.setYnote("9c82bf470cba7bd2f1819b0ee26f86c6ce670e9b");
    }

//    private fun initDoubleClick() {
//        ViewDoubleHelper.init(this, 500)
//    }

    private fun initUMPush() {
        //获取消息推送代理示例
//        val mPushAgent = PushAgent.getInstance(this)
        //注册推送服务，每次调用register方法都会回调该接口
//        mPushAgent.register(object : IUmengRegisterCallback {
//            override fun onSuccess(deviceToken: String) {
//                LogUtils.d("deviceToken====$deviceToken")
//            }
//
//            override fun onFailure(s: String, s1: String) {}
//        })
//        mPushAgent.messageHandler = FcjMessageHandler()
//        mPushAgent.notificationClickHandler = FcjNotificationClickHandler()
    }

    //    private void initBugly() {
//        Bugly.init(this, BizConstant.BUGLY_APPKEY, BuildConfig.DEBUG);
////        CrashReport.setIsDevelopmentDevice(this, BuildConfig.DEBUG);
//        CrashReport.setAppChannel(getApplicationContext(), ChannelUtil.getChannel(this, "DEFAULT_CHANNEL"));
//        CrashReport.setAppVersion(getApplicationContext(), com.blankj.utilcode.util.AppUtils.getAppVersionName());
//        CrashReport.initCrashReport(getApplicationContext(), BizConstant.BUGLY_APPKEY, BuildConfig.DEBUG);
//    }
    private fun initDir() {
        AppConstants.BizKey.DIR_APK = "$filesDir/apk"
    }

    private fun initUIKit() {
        val options: SDKOptions = NimSDKOptionConfig.getSDKOptions(this, DataUtils.readAppKey(this))
        IMKitClient.init(this, null, options)
//        ALog.d(Constant.PROJECT_TAG, com.netease.yunxin.app.im.IMApplication.TAG, "initUIKit")
        if (isMainProcess(this)) {
//            ALog.d(
//                Constant.PROJECT_TAG,
//                com.netease.yunxin.app.im.IMApplication.TAG,
//                "initUIKit:isMainProcess"
//            )
//            LocationKitClient.init()
            //huawei push
//            ActivityMgr.INST.init(this)
            //oppo push
//            HeytapPushManager.init(this, true)
//            try {
//                //vivo push
//                PushClient.getInstance(this).initialize()
//            } catch (e: VivoPushException) {
//                e.printStackTrace()
//            }
            toggleNotification(isPushNotify())
            registerMixPushMessageHandler(PushMessageHandler())

        }
    }
}